<template>
  <div class="app-container">
    <el-button v-waves type="primary" @click="handleAdd">添加职务</el-button>

    <el-table
      :data="table.data"
      row-key = "dutyId"
      v-loading="table.listLoading"
      style="width: 100%;margin-top:30px;"
      border
    >
      <el-table-column align="center" label="职务名称">
        <template slot-scope="scope">
          {{ scope.row.dutyName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="职务代码">
        <template slot-scope="scope">
          {{ scope.row.dutyCode }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属职位">
        <template slot-scope="scope">
          {{ formatPostName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="职务说明">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" width="180px">
        <template slot-scope="scope">
          <el-button v-waves type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button v-waves type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="table.total > 0" :total="table.total" :page.sync="table.listQuery.page" :pageSizes.sync="table.pageSizes"  :limit.sync="table.listQuery.limit" @pagination="getTableList" />
    <el-dialog :visible.sync="dialog.visible" :title="dialog.title">
      <el-form :model="duty" label-width="80px" label-position="left" style="margin: 0px 20px 0px 20px">
        <el-form-item label="职务名称">
          <el-input v-model="duty.dutyName" placeholder="职务名称" />
        </el-form-item>
        <el-form-item label="职务代码">
          <el-input v-model="duty.dutyCode" placeholder="职务代码" />
        </el-form-item>
        <el-form-item label="所属职位">
          <el-select v-model="duty.postId" placeholder="请选择">
            <el-option
              v-for="item in positions"
              :key="item.positionId"
              :label="item.positionName"
              :value="item.positionId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位说明">
          <el-input
            v-model="duty.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="职务说明"
          />
        </el-form-item>
        <el-form-item label="资源权限">
          <el-tree
            ref="resourcesTree"
            :check-strictly="tree.checkStrictly"
            :data="tree.data"
            :props="tree.props"
            show-checkbox
            node-key="key"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialog.visible=false">取消</el-button>
        <el-button type="primary" @click="confirmSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { deepClone } from '@/utils'
import { list } from '@/api/position'
import { getPermissionTree } from '@/api/role'
import { searchDuty, dutyInfo, addDuty, editDuty, disableDuty } from '@/api/duty'

const defaultDuty = {
  dutyId: null,
  dutyCode: null,
  dutyName: null,
  postId: null,
  permissions: []
}

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      table: {
        total: 0,
        data: [],
        listLoading: true,
        pageSizes: [10, 20, 30, 50, 100],
        listQuery: {
          page: 1,
          limit: 10,
          sort: ''
        }
      },
      tree: {
        data: [],
        checkStrictly: false,
        props: {
          label: 'name',
          children: 'children',
        }
      },
      dialog: {
        visible: false,
        title: '',
        addTitle: '添加职务',
        editTitle: '编辑职务',
        type: '',
        addType: 'add',
        editType: 'edit'
      },
      positions: [],
      duty: deepClone(defaultDuty)
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    try {
      Promise.all([this.getTableList(), this.loadPositions(), this.loadResourceTree()])
    } catch (e) {
      console.log(e)
    }
  },
  methods: {
    async getTableList() { // 得到职位列表
      this.table.listLoading = true
      const res = await searchDuty(this.table.listQuery)
      this.table.data = res.result
      this.table.total = parseInt(res.total)
      this.table.listLoading = false
    },
    handleAdd() { // 执行添加职位
      if (this.$refs.resourcesTree) { // clear tree
        this.$refs.resourcesTree.setCheckedNodes([])
      }
      this.duty = deepClone(defaultDuty)
      this.dialog.type = this.dialog.addType
      this.dialog.title = this.dialog.addTitle
      this.dialog.visible = true // open dialog
    },
    async handleEdit(scope) { // 执行修改职位
      if (this.$refs.resourcesTree) { // clear tree
        this.$refs.resourcesTree.setCheckedNodes([])
      }
      this.dialog.type = this.dialog.editType
      this.dialog.title = this.dialog.editTitle
      this.dialog.visible = true // open dialog
      this.tree.checkStrictly = true
      const dutyId = scope.row.dutyId// get Id
      this.duty = await dutyInfo(dutyId)
      this.$nextTick(() => {
        this.duty.permissions.forEach((item) => {
          this.$refs.resourcesTree.setChecked(item.resourceId, true)
        })
        this.tree.checkStrictly = false
      })
    },
    handleDelete({ $index, row }) { // 执行删除职位
      this.$confirm('确认删除该职务 ?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await disableDuty(row.dutyId)
          this.table.data.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
        .catch(err => { console.error(err) })
    },
    async confirmSave() { // 提交新增或修改
      let notifyTitle = ''
      const checkedNodes = this.$refs.resourcesTree.getCheckedNodes() // 获得选中的权限
      this.duty.permissions = [] // clear array
      checkedNodes.forEach((item) => { // 添加权限对象
        if (item.nodeType !== 'management') {
          this.duty.permissions.push({
            'resourceId': item.resourceId,
            'permission': item.permission
          })
        }
      })
      if (this.dialog.type === this.dialog.addType) {
        notifyTitle = '添加成功'
        await addDuty(this.duty)
      }
      if (this.dialog.type === this.dialog.editType) {
        notifyTitle = '修改成功'
        await editDuty(this.duty)
      }
      const { dutyName, dutyCode } = this.duty
      const notify = { // notify
        title: `${notifyTitle}`,
        type: 'success',
        dangerouslyUseHTMLString: true,
        message: `<div>职务名称: ${dutyName}</div> <div>职务代码: ${dutyCode}</div>`
      }
      this.$notify(notify)
      this.dialog.visible = false// close dialog
      this.getTableList() // reload table
    },
    async loadPositions() { // 加载职位列表
      this.positions = await list()
    },
    formatPostName(duty) {
      if (duty.position) {
        return duty.position.positionName
      }
      return ''
    },
    async loadResourceTree() { // 加载资源权限树
      const res = await getPermissionTree()
      this.tree.data = res.map((item, index, array) => {
        item.key = item.managementId;
        if (item.nodes) {
          item.nodes.forEach((item, index) => {
            item.key = item.resourceId
            item.name = item.resourceName
          })
          item.children.push(...item.nodes)
        }
        return item
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
